package com.distribute.core.notify.redis.redisTemplate;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.distribute.core.core.BaseNotifyMessage;
import com.distribute.core.notify.redis.RedisMessageListenerUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 接受通知消息，刷新缓存实现类
 * 初始化 channel
 *
 * @author chennengcheng
 * @date 2021-09-17 17:19
 * @remark
 */
public class RedisTemplateNotifyMessageListener extends MessageListenerAdapter {

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String msg = RedisSerializer.string().deserialize(message.getBody());
        if (StrUtil.isEmpty(msg)) {
            return;
        }

        boolean contains = msg.contains("\"") && msg.contains("\"{") && msg.contains("}\"") ;
        if (contains) {
            msg = msg.replaceAll("\\\\", "");
            msg = msg.replaceAll("\"\\{", "{");
            msg = msg.replaceAll("\\}\"", "}");
        }

        BaseNotifyMessage redisBaseNotifyMessage = JSONUtil.toBean(msg, BaseNotifyMessage.class);
        RedisMessageListenerUtils.process(redisBaseNotifyMessage);
    }
}